<template>
	<div class="from">
		<h1>注册</h1>
		<el-form
			:model="ruleForm"
			status-icon
			:rules="rules"
			ref="ruleForm"
			label-width="100px"
			class="demo-ruleForm"
		>
			<el-form-item label="昵称" prop="username">
				<el-input v-model="ruleForm.username"></el-input>
			</el-form-item>
			<el-form-item label="邮箱" prop="email">
				<el-input v-model="ruleForm.email"></el-input>
			</el-form-item>
			<el-form-item label="密码" prop="password">
				<el-input
					type="password"
					v-model="ruleForm.password"
					autocomplete="off"
				></el-input>
			</el-form-item>
			<el-form-item label="确认密码" prop="checkPass">
				<el-input
					type="password"
					v-model="ruleForm.checkPass"
					autocomplete="off"
				></el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="submitForm('ruleForm')"
					>提交</el-button
				>
				<el-button @click="resetForm('ruleForm')">重置</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
	export default {
		name: "RegisterView",
		data() {
			var checkUser = (rule, value, callback) => {
				console.log("用户名:", value);
				if (value.trim() == "") {
					callback(new Error("请输入昵称"));
				} else {
					callback();
				}
			};
			var checkEmail = (rule, value, callback) => {
				console.log("邮箱:", value);
				if (value.trim() == "") {
					callback(new Error("请输入邮箱"));
				} else {
					callback();
				}
			};
			var validatePass = (rule, value, callback) => {
				console.log("密码：", value);
				if (value.trim() == "") {
					callback(new Error("请输入密码"));
				} else {
					callback();
				}
			};
			var validatePass2 = (rule, value, callback) => {
				if (value === "") {
					callback(new Error("请再次输入密码"));
				} else if (value !== this.ruleForm.password) {
					callback(new Error("两次输入密码不一致!"));
				} else {
					callback();
				}
			};
			return {
				ruleForm: {
					password: "",
					username: "",
					email: "",
					checkPass: "",
				},
				rules: {
					password: [{ validator: validatePass, trigger: "blur" }],
					username: [{ validator: checkUser, trigger: "blur" }],
					email: [{ validator: checkEmail, trigger: "blur" }],
					checkPass: [{ validator: validatePass2, trigger: "blur" }],
				},
			};
		},
		methods: {
			submitForm(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						alert("submit!");
					} else {
						console.log("error submit!!");
						return false;
					}
				});
			},
			resetForm(formName) {
				this.$refs[formName].resetFields();
			},
		},
	};
</script>

<style>
	.from {
		width: 500px;
		margin: 30px auto;
	}
	h1 {
		text-align: center;
		margin-bottom: 10px;
	}
</style>